package client.domain.ui.centerPanel.chart;

import client.domain.Chart;
import static client.domain.SandboxMainKeys.*;
import client.internationalization.SandboxConstants;
import client.internationalization.SandboxMessages;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.PopupPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.ExtElement;
import com.gwtext.client.data.*;
import com.gwtext.client.widgets.*;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.ColorPaletteListenerAdapter;
import com.gwtext.client.widgets.form.*;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.grid.*;
import com.gwtext.client.widgets.layout.*;

/**
 * User: nbarrios
 * Date: Nov 16, 2009
 */
public class CreateChartWizard extends Window{

	//	Internationalization Strings
	private SandboxConstants constants = GWT.create(SandboxConstants.class);
	private static SandboxMessages messages = GWT.create(SandboxMessages.class);

	//	Attributes
	private Chart newChart;

	private Panel mainPanel = new Panel();
	private final Panel wizardPanel = new Panel();
	private ComboBox chartsTypeComboBox = new ComboBox();

	private ToolbarButton backButton;// = new ToolbarButton(constants.back(), listener);
	private ToolbarButton nextButton;

	private Panel firstCard = null;
		private Panel firstCardRootPanel = null;
	private Panel secondCard = null;
		private Panel secondCardRootPanel = null;
			private Label secondCardLabel;
			private static TextField width;
			private static TextField height;
	private Panel thirdCard = null;
		private Panel thirdCardRootPanel = null;
			private EditorGridPanel chartPropertiesGrid;
	private Panel fourthCard = null;
		private Panel fourthCardRootPanel = null;


	/**
	 * Create a new Window.
	 */
	public CreateChartWizard() {
		this.setTitle(constants.createChartWizardPopUpTitle());
		this.setSize(CHART_WIZARD_WIDTH, CHART_WIZARD_HEIGHT);
		this.setAutoHeight(true);

		mainPanel.setBorder(false);
		mainPanel.setLayout(new FitLayout());

        wizardPanel.setLayout(new CardLayout());
        wizardPanel.setActiveItem(0);
		wizardPanel.setBorder(false);

		//	Create the listener to the back and next buttons
		ButtonListenerAdapter listener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
                String buttonID = button.getId();
				handleBackAndNextButtonsEvents(buttonID);
            }
        };

		//	Add the toolbar with the back and next buttons
		Toolbar toolbar = new Toolbar();

		backButton = new ToolbarButton(constants.back(), listener);
        backButton.setId(BACK_BUTTON_ID);
        toolbar.addButton(backButton);
		toolbar.addFill();

		nextButton = new ToolbarButton(constants.next(), listener);
		nextButton.setId(NEXT_BUTTON_ID);
		toolbar.addButton(nextButton);

//		toolbar.setHeight("25px");
		toolbar.addFill();

		wizardPanel.setBottomToolbar(toolbar);


		createFristCardUI();
        wizardPanel.add(firstCard);

        mainPanel.add(wizardPanel);
		this.add(mainPanel);
	}

	/**
	 * Control the back and next button events when the user clicks them
	 * @param buttonID	The button ID of the listened event.
	 */
	private void handleBackAndNextButtonsEvents(String buttonID) {
		CardLayout cardLayout = (CardLayout) wizardPanel.getLayout();
		String panelID = cardLayout.getActiveItem().getId();


		if (buttonID.equals(BACK_BUTTON_ID)) {
			//	Here the event comes from "Back" button
			if (panelID.equals(CHART_WIZARD_CARD_2)) {
				//	Return to the first card
				cardLayout.setActiveItem(0);
				backButton.hide();
				nextButton.enable();
			}
			else if (panelID.equals(CHART_WIZARD_CARD_3))
				//	Return to the second card
				cardLayout.setActiveItem(1);
			else if (panelID.equals(CHART_WIZARD_CARD_4)){
				//	Return to the fourth card and change the label of the "nextButton" from "Create it now!" to "Next" because is the last card.
				cardLayout.setActiveItem(2);
				nextButton.setText(constants.next());
			}
		}
		else {
			//	Here the event comes from "Next" button
			if (panelID.equals(CHART_WIZARD_CARD_1)) {
//				newChart = new Chart(chartsTypeComboBox.getValue());
//				chartsTypeComboBox.getRawValue();
//				chartsTypeComboBox.getStore().getById(Chart.CHART_PARAMETER_TYPE_VALUE_GOOGLE_O_METE).getAsString(CHART_TYPE_ID);//  TODO:   ver porque me toma siempre el valor que no muestro en el combo

				createSecondCardUI();

				wizardPanel.add(secondCard);
				cardLayout.setActiveItem(1);//	Go to the second card
				backButton.show();
			}
			else if (panelID.equals(CHART_WIZARD_CARD_2) && validateSecondCardParameters()){
				createThirdCardUI();
				wizardPanel.add(thirdCard);
				cardLayout.setActiveItem(2);//	Go to the third card
			}
			else if (panelID.equals(CHART_WIZARD_CARD_3)){
				//	Go to the fourth card and change the label of the "nextButton" from "Next" to "Create it now!" because is the last card.
				createFourthCardUI();

				wizardPanel.add(fourthCard);
				cardLayout.setActiveItem(3);

				nextButton.setText(constants.createItNow());
			}
		}

		wizardPanel.doLayout();

	}

	/**
	 * Create the UI for the first card of the "Create Card Wizard"
	 */
	private void createFristCardUI() {

		if(firstCard==null){
			firstCard = customizeANewCardPanel(firstCard, CHART_WIZARD_CARD_1, CHART_WIZARD_CARD_1_INDEX, DEFAULT_PADDINGS);
			firstCardRootPanel = customizeANewCardRootPanel(firstCardRootPanel, new VerticalLayout(DEFAULT_VERTICAL_SPACE_BETWEEN_WIDGETS));
		}


		chartsTypeComboBox.setForceSelection(true);
		chartsTypeComboBox.setEmptyText(constants.chooseOne());

		Store chartsTypeStore = new SimpleStore(
				new String[]{CHART_NAME, CHART_TYPE_ID}
				, this.getChartTypes()
		);
		chartsTypeComboBox.setStore(chartsTypeStore);
		chartsTypeComboBox.setDisplayField(CHART_NAME);
		chartsTypeComboBox.addListener(new ComboBoxListenerAdapter(){
			public void onSelect(ComboBox comboBox, Record record, int index) {
				super.onSelect(comboBox, record, index);
				if(nextButton.isDisabled())
					nextButton.enable();
			}
		});

		firstCardRootPanel.add(new Label(constants.chooseTheTypeOfChartYouWantToCreate()));
		firstCardRootPanel.add(chartsTypeComboBox);

		backButton.hide();
		nextButton.disable();

		firstCard.add(firstCardRootPanel);
	}

	/**
	 * Create the UI for the second card of the "Create Card Wizard"
	 */
	private void createSecondCardUI() {

		//	Prepare the constants for the label.
		String maximumArea;
		final String maximumWidth;
		final String maximumHeight;
		if(chartsTypeComboBox.getValue().equals(Chart.CHART_NAME_MAP)){
			maximumArea = MAXIMUM_PIXELS_FOR_MAPS;
			maximumWidth = String.valueOf(MAXIMUM_WIDTH_FOR_MAPS);
			maximumHeight = String.valueOf(MAXIMUM_HEIGHT_FOR_MAPS);
		}
		else{
			maximumArea = MAXIMUM_AREA_FOR_SIMPLE_CHARTS_PX;
			maximumWidth = String.valueOf(MAXIMUM_WIDTH_OR_HEIGHT_FOR_SIMPLE_CHARTS);
			maximumHeight = String.valueOf(MAXIMUM_WIDTH_OR_HEIGHT_FOR_SIMPLE_CHARTS);
		}
		String labelText = messages.selectTheSizeForTheChart(chartsTypeComboBox.getValue(), maximumArea, maximumWidth, maximumHeight);

		if(secondCard==null){
			secondCard = customizeANewCardPanel(secondCard, CHART_WIZARD_CARD_2, CHART_WIZARD_CARD_2_INDEX, 0);
			secondCardRootPanel = customizeANewCardRootPanel(secondCardRootPanel, new FitLayout());

			secondCardLabel = new Label(labelText);

			//	Create the FormPanel and set the label position to top
			FormPanel formPanel = new FormPanel();
			formPanel.setFrame(true);
			formPanel.setPaddings(0, 0, 0, 0);

			//	Create top panel with ColumnLayout
//			Panel topPanel = new Panel();
//			topPanel.setLayout(new ColumnLayout());

			//	Create the column and add fields to it
			Panel columnOnePanel = new Panel();
			columnOnePanel.setLayout(new FormLayout());

			columnOnePanel.add(secondCardLabel);

			width = new TextField(constants.width(), "width");
			width.setAllowBlank(false);
			width.setTabIndex(0);
			width.setBlankText(constants.thisFieldIsRequired());
			width.setInvalidText(messages.widthOrHeightCanNotBeGreaterThan(constants.width(), maximumWidth));
			width.setValidator(new Validator(){
				public boolean validate(String value) throws ValidationException {
					return Integer.parseInt(value) <= Integer.parseInt(maximumWidth);
				}
			});
			columnOnePanel.add(width, new AnchorLayoutData("80%"));



			height = new TextField(constants.height(), "height");
			height.setAllowBlank(false);
			height.setTabIndex(1);
			height.setBlankText(constants.thisFieldIsRequired());
			height.setInvalidText(messages.widthOrHeightCanNotBeGreaterThan(constants.height(), maximumHeight));
			height.setValidator(new Validator(){
				public boolean validate(String value) throws ValidationException {
					return Integer.parseInt(value) <= Integer.parseInt(maximumHeight);
				}
			});
			columnOnePanel.add(height, new AnchorLayoutData("80%"));


			//add panel as column with 100% of the form width
//			topPanel.add(columnOnePanel, new ColumnLayoutData(1));
//			formPanel.add(topPanel);

			formPanel.add(columnOnePanel);

			secondCardRootPanel.add(formPanel);
//			secondCardRootPanel.doLayout();
			
			secondCard.add(secondCardRootPanel);
		}
		else
		    secondCardLabel.setText(labelText);


	}

	/**
	 * Create the UI for the third card of the "Create Card Wizard"
	 */
	private void createThirdCardUI() {
		if(thirdCard==null){
			thirdCard = customizeANewCardPanel(thirdCard, CHART_WIZARD_CARD_3, CHART_WIZARD_CARD_3_INDEX, DEFAULT_PADDINGS);
			thirdCardRootPanel = customizeANewCardRootPanel(thirdCardRootPanel, new VerticalLayout(DEFAULT_VERTICAL_SPACE_BETWEEN_WIDGETS));

			thirdCardRootPanel.add(new Label(constants.thirdCardLabel()));


			final RecordDef recordDef = new RecordDef(
                new FieldDef[]{
                	new StringFieldDef(DATA_INDEX_LABEL)
                    , new IntegerFieldDef(DATA_INDEX_VALUE)
					, new StringFieldDef(DATA_INDEX_COLOUR)
                }
        	);

//			MemoryProxy proxy = new MemoryProxy(new Object[1][3]);                                                                    , 
			MemoryProxy proxy = new MemoryProxy(new Object[][]{
					new Object[]{"un label", "123", "FFAAFF"}
					, new Object[]{"otro label", "156", "AAFFAA"}
			});

			ArrayReader reader = new ArrayReader(recordDef);
			final Store store = new Store(proxy, reader);
			store.load();

			//	The label column
			ColumnConfig labelColumn = new ColumnConfig(constants.label(), DATA_INDEX_LABEL, 35, false);
//			labelColumn.setWidth(100);
			TextField textFieldLabel = new TextField();
//			textFieldLabel.setWidth(90);
			labelColumn.setEditor(new GridEditor(new TextField()));

			//	The value column
			ColumnConfig valueColumn = new ColumnConfig(constants.value(), DATA_INDEX_VALUE, 35, false);
//			valueColumn.setWidth(100);
			NumberField numberField = new NumberField();
			numberField.setAllowDecimals(false);
			numberField.setBlankText(constants.thisFieldIsRequired());
			numberField.setAllowBlank(false);
			numberField.setAllowNegative(false);
//			numberField.setWidth(90);
			valueColumn.setEditor(new GridEditor(numberField));

//			//	The colour column
//			ColumnConfig colourColumn = new ColumnConfig(constants.colour(), DATA_INDEX_COLOUR, 55, false);
//			final TextField colourTextField = new TextField();
//			colourTextField.addListener(new TextFieldListenerAdapter(){
//				@Override
//				public void onFocus(Field field) {
//					super.onFocus(field);
//
//					final PopupPanel colourPopUp = new PopupPanel();
//
//					com.google.gwt.user.client.Window.alert("ahora mostraria!");
//
//					ColorPalette colorPalette = new ColorPalette();
//					colorPalette.addListener(new ColorPaletteListenerAdapter() {
//						public void onSelect(ColorPalette colorPalette, String color) {
//							colourTextField.getFieldLabel();
//							colourTextField.getText();
//							colourTextField.getRawValue();
//
//
//							colourTextField.setStyle("background-color:" + color + ";background-image:none;");
//							colourTextField.setValue(color);
//							colourPopUp.hide();
//						}
//
//					});
//
//
//
//
//
//					colourPopUp.add(colorPalette);
//					colourPopUp.showRelativeTo(field);
//				}
//			});
//
//			labelColumn.setEditor(new GridEditor(colourTextField));



			//	The colour column
			final ColorPalette colorPalette = new ColorPalette();
			final PopupPanel colourPopUp = new PopupPanel();
			colourPopUp.add(colorPalette);
			colourPopUp.setAutoHideEnabled(true);


			ColumnConfig colourColumn = new ColumnConfig(constants.colour(), DATA_INDEX_COLOUR, 55);
//			colourColumn.setWidth(100);
			final TriggerField colourField = new TriggerField(){
				/**
				 * Abstract method that must be implmented for custom trigger field behavior.
				 * @param event the event object
				 */
				protected void onTriggerClick(EventObject event) {
					colourPopUp.show();
				}
			};




			colorPalette.addListener(new ColorPaletteListenerAdapter() {
				public void onSelect(ColorPalette colorPalette, String color) {
					colourField.setValue(color);
					colourPopUp.hide();
				}
			});

			colourField.setWidth(90);
			colourColumn.setEditor(new GridEditor(colourField));

			BaseColumnConfig[] columns = new BaseColumnConfig[]{
					new RowNumberingColumnConfig()
					, labelColumn
					, valueColumn
					, colourColumn
			};

			ColumnModel columnModel = new ColumnModel(columns);

			chartPropertiesGrid = new EditorGridPanel();
			chartPropertiesGrid.setStore(store);
			chartPropertiesGrid.setAutoHeight(true);
			chartPropertiesGrid.setWidth(330);
			chartPropertiesGrid.setColumnModel(columnModel);
			chartPropertiesGrid.setClicksToEdit(DEFAULT_CLICKS_TO_EDIT_GRID);
			chartPropertiesGrid.setTitle(constants.chartPropertiesGridTitle());
			chartPropertiesGrid.setIconCls("grid-icon");

			chartPropertiesGrid.setTools(new Tool[]{	new Tool(Tool.PLUS, new ToolHandler(){
															public void onClick(EventObject e, ExtElement toolEl, Panel panel) {
																Record property = recordDef.createRecord(	new Object[]{null, null, null}	);
																int rowNumber = chartPropertiesGrid.getStore().getCount();

																chartPropertiesGrid.stopEditing();
																store.insert(rowNumber, property);
//																chartPropertiesGrid.startEditing(0, 0);
															}
														})
													}
										);

			GridView view = new GridView();
			view.setForceFit(true);
			chartPropertiesGrid.setView(view);

			thirdCardRootPanel.add(chartPropertiesGrid);

			thirdCard.add(thirdCardRootPanel);
		}
	}

	/**
	 * Create the UI for the fourth card of the "Create Card Wizard"
	 */
	private void createFourthCardUI() {

		fourthCard = customizeANewCardPanel(fourthCard, CHART_WIZARD_CARD_4, CHART_WIZARD_CARD_4_INDEX, DEFAULT_PADDINGS);
		fourthCardRootPanel = customizeANewCardRootPanel(fourthCardRootPanel, new VerticalLayout(DEFAULT_VERTICAL_SPACE_BETWEEN_WIDGETS));



		//	Creo el chart










		fourthCardRootPanel.add(new Label("un preview para ver como queda"));

		fourthCard.add(fourthCardRootPanel);
	}

	/**
	 * Sets the basic and commons features of every card panel.
	 * @param cardPanel	The cardPanel to customize.
	 * @param cardID	The cardPanel ID.
	 * @param cardIndex	The card index in the wizard sequence.
	 * @return			The cardPanel customized.
	 */
	private static Panel customizeANewCardPanel(Panel cardPanel, String cardID, int cardIndex, int paddings) {
		cardPanel = new Panel();
		cardPanel.setId(cardID);
		cardPanel.setBorder(false);
		cardPanel.setHeight(CHART_WIZARD_HEIGHT-DEFAULT_TITLE_HEIGHT-DEFAULT_TOOLBAR_HEIGHT);
		cardPanel.setTitle(messages.stepNOfM(cardIndex, CHART_WIZARD_TOTAL_CARDS));
		cardPanel.setLayout(new FitLayout());
		cardPanel.setPaddings(paddings);

		return cardPanel;
	}

	/**
	 * Sets the basic and commons features of every card main panel.
	 * @param cardRootPanel	The cardPanel to customize.
	 * @return			The cardPanel customized.
	 */
	private static Panel customizeANewCardRootPanel(Panel cardRootPanel, ContainerLayout layout){
		cardRootPanel = new Panel();
		cardRootPanel.setLayout(layout);
		cardRootPanel.setBorder(false);
		cardRootPanel.setPaddings(0);

		return cardRootPanel;
	}

	/**
	 * Get the different type of charts that can be created.
	 * @return	An array of arrays containing the couple of chart type and chart name
	 */
	private String[][] getChartTypes() {
//		return new String[][]{
//				new String[]{}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_GOOGLE_O_METE, Chart.CHART_NAME_GOOGLE_O_METE}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_HORIZONTAL_BAR, Chart.CHART_NAME_HORIZONTAL_BAR}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_LINE_CHART, Chart.CHART_NAME_LINE_CHART}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_MAP, Chart.CHART_NAME_MAP}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_PIE_2D, Chart.CHART_NAME_PIE_2D}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_PIE_3D, Chart.CHART_NAME_PIE_3D}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_POINTS, Chart.CHART_NAME_POINTS}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_RADAR_CURVED_LINES, Chart.CHART_NAME_RADAR_CURVED_LINES}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_RADAR_STRAIGHT_LINES, Chart.CHART_NAME_RADAR_STRAIGHT_LINES}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_SOME_LINES_CHART, Chart.CHART_NAME_SOME_LINES_CHART}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_VENN, Chart.CHART_NAME_VENN}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_VERTICAL_BAR, Chart.CHART_NAME_VERTICAL_BAR}
//				, new String[]{Chart.CHART_PARAMETER_TYPE_VALUE_WORD_GRAPH, Chart.CHART_NAME_WORD_GRAPH}
//		};
		return new String[][]{
				new String[]{}
				, new String[]{Chart.CHART_NAME_GOOGLE_O_METE, 			Chart.CHART_PARAMETER_TYPE_VALUE_GOOGLE_O_METE}
				, new String[]{Chart.CHART_NAME_HORIZONTAL_BAR, 		Chart.CHART_PARAMETER_TYPE_VALUE_HORIZONTAL_BAR}
				, new String[]{Chart.CHART_NAME_LINE_CHART, 			Chart.CHART_PARAMETER_TYPE_VALUE_LINE_CHART}
				, new String[]{Chart.CHART_NAME_MAP, 					Chart.CHART_PARAMETER_TYPE_VALUE_MAP}
				, new String[]{Chart.CHART_NAME_PIE_2D, 				Chart.CHART_PARAMETER_TYPE_VALUE_PIE_2D}
				, new String[]{Chart.CHART_NAME_PIE_3D, 				Chart.CHART_PARAMETER_TYPE_VALUE_PIE_3D}
				, new String[]{Chart.CHART_NAME_POINTS, 				Chart.CHART_PARAMETER_TYPE_VALUE_POINTS}
				, new String[]{Chart.CHART_NAME_RADAR_CURVED_LINES, 	Chart.CHART_PARAMETER_TYPE_VALUE_RADAR_CURVED_LINES}
				, new String[]{Chart.CHART_NAME_RADAR_STRAIGHT_LINES, 	Chart.CHART_PARAMETER_TYPE_VALUE_RADAR_STRAIGHT_LINES}
				, new String[]{Chart.CHART_NAME_SOME_LINES_CHART, 		Chart.CHART_PARAMETER_TYPE_VALUE_SOME_LINES_CHART}
				, new String[]{Chart.CHART_NAME_VENN, 					Chart.CHART_PARAMETER_TYPE_VALUE_VENN, }
				, new String[]{Chart.CHART_NAME_VERTICAL_BAR, 			Chart.CHART_PARAMETER_TYPE_VALUE_VERTICAL_BAR}
				, new String[]{Chart.CHART_NAME_WORD_GRAPH, 			Chart.CHART_PARAMETER_TYPE_VALUE_WORD_GRAPH}
		};
	}

	private boolean validateSecondCardParameters(){
		return width.isValid() && height.isValid();
	}

}//  End Class
